<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\QrCodeController;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户微信信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    public $table = 'user_info';

    public function getTable()
    {
        return $this->table;
    }

    /*关联微信账号*/
    public function conWechat()
    {
        return $this->hasOne(UserWechatInfo::class, 'id', 'wechat_id');
    }


    /*关联图书馆账号*/
    public function conLibrary()
    {
        return $this->hasOne(UserLibraryInfo::class, 'id', 'account_id');
    }

    /*关联用户预约申请记录*/
    public function conReservation()
    {
        //return $this->hasMany(ReservationApply::class, 'user_id', 'id');
    }

    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public static function getWechatField($user_id, $field)
    {
        $wechat_id = self::where('id', $user_id)->value('wechat_id');
        return UserWechatInfo::where('id', $wechat_id)->value($field);
    }
    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public function getUserInfoByWechatId($wechat_id, $field = null)
    {
        $res = $this->where('wechat_id', $wechat_id)->first();
        if ($res && $field && !empty($res[$field])) {
            return $res[$field];
        }
        return $res;
    }


    /**
     * 判断用户是否存在
     * @param user_guid 用户guid
     */
    public function getUserInfo($user_guid)
    {
        $res = $this->where('token', $user_guid)->first();
        if (empty($res)) {
            return false;
        }

        return $res;
    }

    /**
     * 根据用户id，获取微信信息
     * @param user_id 用户guid
     */
    public function getUserBaseInfo($user_id)
    {
        $user_info = $this->select('serial_number', 'nickname', 'head_img', 'tel')->where('id', $user_id)->first();
        if ($user_info) {
            $user_info = $user_info->toArray();
            $obj = new Controller();
            $user_info['head_img'] = $obj->getImgAllAddrUrl($user_info['head_img']);
        }
        return $user_info;
    }

    /**
     * 根据用户id，获取微信信息
     * @param user_guid 用户guid
     */
    public function getWechatInfo($user_guid)
    {
        $wechat_id = $this->where('token', $user_guid)->value('wechat_id');
        if (empty($wechat_id)) {
            return false;
        }
        $wechat_info = UserWechatInfo::select('nickname', 'head_img', 'tel')->where('id', $wechat_id)->first();
        return $wechat_info ? $wechat_info->toArray() : null;
    }
    /**
     * 根据用户id，获取读者证号信息
     * @param user_guid 用户guid
     */
    public function getAccountInfo($user_guid)
    {
        $account_id = $this->where('token', $user_guid)->value('account_id');
        if (empty($account_id)) {
            return false;
        }

        $account_info = UserLibraryInfo::select('account')->where('id', $account_id)->first();
        return $account_info ? $account_info->toArray() : null;
    }

    /**
     * 获取用户guid  根据关键字
     * @param keywords  微信昵称检索
     */
    public function getUserGuidByKeywords($keywords)
    {
        $wechat_id = UserWechatInfo::where('nickname', 'like', $keywords . '%')->value('id');
        if (empty($wechat_id)) {
            return false;
        }
        $user_guid = $this->where('wechat_id', $wechat_id)->value('token');
        return $user_guid;
    }



    /**关联书籍信息 */
    public function conBookRead()
    {
        //  return $this->hasMany(AudioBookRead::class, 'user_id', 'id');
    }

    /**
     * 根据user_id 获取读者证号id
     */
    public function getAccountId($user_id)
    {
        $account_id = $this->where('id', $user_id)->value('account_id');
        if (empty($account_id)) {
            return false; //未绑定
        }
        return $account_id;
    }
    /**
     * 根据account_id 获取用户id
     */
    public function getUserIdByAccount($account_id)
    {
        $id = $this->where('account_id', $account_id)->value('id');
        if (empty($id)) {
            return false; //未绑定
        }
        return $id;
    }
    /**
     * 获取用户随机编号
     */
    public function getUserRandomSerialNumber()
    {
        $i = 10;
        while ($i) {
            $serial_number = 'U' . get_rnd_number(10);
            //判断qr_code是否重复
            $qr_code_exist = $this->where('serial_number', $serial_number)->first();
            if ($qr_code_exist) {
                $i--;
            } else {
                return $serial_number;
            }
        }
        return false;
    }

    /**
     * 读者证号绑定在用户信息上
     */
    public function setAccountBindUserInfo($account_id, $wechat_id = null)
    {
        $user_info = $this->where('account_id', $account_id)->first();

        if (empty($user_info)) {
            $this->account_id = $account_id;
            $this->token = get_guid();

            $qrCodeObj = new QrCodeController();
            $qr_code = $qrCodeObj->getQrCode('user_info');

            $this->qr_code = $qr_code;
            $this->qr_url = $qrCodeObj->setQr($qr_code, true);

            if ($wechat_id)  $this->wechat_id = $wechat_id;

            $this->save();
            $token = $this->token;
            $id = $this->id;
        } else {
            if ($wechat_id && $user_info->wechat_id != $wechat_id) {
                $user_info->wechat_id = $wechat_id;
                $user_info->save();
            }

            $token = $user_info->token;
            $id = $user_info->id;
        }

        return ['token' => $token, 'id' => $id];
    }

    /**
     * 用户列表
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序
     */
    public function lists($keywords, $start_time, $end_time, $sort = 1, $limit = 10)
    {
        $sort = $sort == 2 ? 'score' : 'create_time';

        $res = $this->select('id', 'account_id', 'serial_number', 'tel', 'nickname', 'head_img', 'create_time', 'invite_number')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('serial_number', 'like', "%$keywords%")
                        ->Orwhere('tel', 'like', "%$keywords%")
                        ->Orwhere('nickname', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->orderByDesc($sort)
            ->paginate($limit)
            ->toArray();

        $resourceUserReadBookDayModel = new ResourceUserReadBookDay();
        $userLibraryInfoModel = new UserLibraryInfo();
        foreach ($res['data'] as $key => $val) {
            if ($val['account_id']) {
                $user_library_info = $userLibraryInfoModel->select('score', 'account')->where('id', $val['account_id'])->first();
                $res['data'][$key]['account'] = $user_library_info['account'];
                $res['data'][$key]['score'] = $user_library_info['score'];
            } else {
                $res['data'][$key]['account'] = null;
                $res['data'][$key]['score'] = null; //不显示积分
            }
            //获取用户访问天数
            $res['data'][$key]['user_access_day'] = $resourceUserReadBookDayModel->getUserAccessDay($val['id']);
            //获取用户阅读时长
            $res['data'][$key]['user_read_duration'] = $resourceUserReadBookDayModel->getUserReadDuration($val['id']) . ' 分钟';
        }
        return $res;
    }

    /**
     * 获取邀请用户列表
     * @param limit 限制条数 默认为 10
     * @param user_id 用户id
     */
    public function getInviteUserLists($user_id, $limit = 10)
    {
        $res = $this->select('id', 'serial_number', 'invite_user_id', 'invite_score', 'nickname', 'head_img', 'create_time')
            ->where('invite_user_id', $user_id)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }



    /**
     * 用户邀请量统计
     * @param keywords string 搜索关键词
     * @param start_time  开始时间
     * @param end_time  结束时间
     * @param limit  限制数量
     */
    public function getInviteUserStatistics($start_time = null, $end_time = null, $keywords = null, $limit = 10)
    {
        $user_id_all = [];
        if (!empty($keywords)) {
            //获取所有满足条件的用户id
            $user_id_all = $this->where(function ($query) use ($keywords) {
                $query->where('serial_number', 'like', "%$keywords%")
                    ->orWhere('nickname', 'like', "%$keywords%")
                    ->orWhere('tel', 'like', "%$keywords%");
            })->pluck('id');
        }

        $res = $this->select('invite_user_id', 'create_time', DB::raw("count(id) as number"))
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords, $user_id_all) {
                if (!empty($keywords)) {
                    $query->whereIn('id', $user_id_all);
                }
            })
            ->whereNotNull('invite_user_id');
        $total_number = $res->count('id');
        $res = $res->groupBy('invite_user_id')
            ->orderByDesc('number')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            $user_info = $this->getUserBaseInfo($val['invite_user_id']);
            $res['data'][$key]['serial_number'] = $user_info['serial_number'];
            $res['data'][$key]['nickname'] = $user_info['nickname'];
            $res['data'][$key]['head_img'] = $user_info['head_img'];
            $res['data'][$key]['tel'] = $user_info['tel'];
        }
        $res['total_number'] = $total_number;
        return $res;
    }


    /**
     * 获取注册人数（绑定读者证人数）
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $type 1 注册人数  2 绑定读者证人数
     */
    public function getUserNumber($type = 1, $start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($type, $start_time, $end_time) {
            if ($type == 2) {
                $query->whereNotNull('account_id');
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count();
        return $number;
    }


    /**
     * 注册人数统计(折线图)
     * @param start_time  开始时间
     * @param end_time  结束时间
     */
    public function registerStatistics($start_time = null, $end_time = null)
    {
        if (date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as number")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as number")];
        }

        $res = $this->select($field)->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()->toArray();

        return $res;
    }



    /**
     * 清空违规次数
     * @param user_id 读者证id
     * @param node  0 全部清空  1 活动 2 预约
     */
    public function clearViolate($user_id, $node = 0)
    {
        if ($node == 1) {
            $saveWhere = ['activity_violate_num' => 0];
        } elseif ($node == 2) {
            $saveWhere = ['reservation_violate_num' => 0];
        } else {
            $saveWhere = ['activity_violate_num' => 0, 'reservation_violate_num' => 0];
        }
        return $this->where('id', $user_id)->update($saveWhere);
    }

    /**
     * 修改微信昵称和头像
     */
    public function userInfoChange($user_id, $nickname, $head_img)
    {
        $data = [];
        if ($head_img) {
            $controllerObj = new Controller();
            $head_img = strpos($head_img, 'http') !== false ? $head_img : ($controllerObj->getImgAddrUrl() . $head_img);
            $data['head_img'] = $head_img;
        }
        if ($nickname) {
            $data['nickname'] = $nickname;
        }

        $res = $this->where('id', $user_id)->update($data);

        //修改对应微信公众号和微信小程序的bug
        $user_info = $this->where('id', $user_id)->first();
        if (!empty($user_info['wechat_id'])) {
            UserWechatInfo::where('id', $user_info['wechat_id'])->update($data);
        }
        if (!empty($user_info['applet_id'])) {
            UserAppletInfo::where('id', $user_info['applet_id'])->update($data);
        }

        return $res;
    }

    // 生成实例
    public static function getInstance()
    {
        return new self;
    }
}
